<template>
  <div class="content">
    <!-- 搜索栏 -->
    <div class="title">
      <el-form :inline="true" :model="searchParams" class="form" style="margin: 20px 0;">
        <el-form-item label="用户手机号">
          <el-input v-model="searchParams.phone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="searchParams.role" style="width: 100px;" placeholder="请选择用户类型">
            <el-option label="全部" value="" />
            <el-option label="业务员" value="1" />
            <el-option label="普通用户" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>

      
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="tableBody">
      <el-table
        :data="userList"
      >
        <!-- <el-table-column type="selection" width="50" /> -->
        <el-table-column prop="name" label="用户名" width="150" />
        <el-table-column prop="phone" label="手机号" width="200" />
        <el-table-column prop="role" label="用户类型" width="200">
          
          <template #default="scope">
            <el-tag :type="scope.row.role === 1 ? 'primary' : 'info'">
              {{ scope.row.role === 1 ? '业务员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
          <el-table-column label="创建时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="更新时间" width="200">
            <template #default="scope">
              {{ formatDate(scope.row.updateTime) }}
            </template>
          </el-table-column>
        <!-- <el-table-column prop="status" label="状态" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="150" align="center " header-align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin: 10px 0 20px 0;"
    />

    <!-- 新增/修改用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.name" placeholder="请输入用户名" />
        </el-form-item>
        <!-- <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item> -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户类型" prop="role">
          <el-radio-group v-model="userForm.role">
            <el-radio :value="0">普通用户</el-radio>
            <el-radio :value="1">业务员</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-switch v-model="userForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserListApi, updateUserApi, deleteUserApi } from '../api/user'
// 搜索参数
const searchParams = reactive({
  phone: "",
  role:""
})

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户列表数据
const userList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const userForm = ref({
  id: null,
  name: '',
  phone: '',
  role:0,
})
const userFormRef = ref(null)
const userFormRules = {
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  role: [{ required: true, message: '请输入身份', trigger: 'change' }],
}

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 初始化加载数据
onMounted(() => {
  search()
})

// 搜索用户
const search = async () => {
  try {
    const params = {
      // currentPage: pagination.value.currentPage,
      // pageSize: pagination.value.pageSize,
      phone: searchParams.phone,
      role: searchParams.role
    };
    const result = await UserListApi(pagination.value.currentPage,pagination.value.pageSize,params)
    //  const result = await UserListApi()
    
    if (result.code === 200) {
      userList.value = result.data.records
      // pagination.total = result.data.total
    } else {
      ElMessage.error(result.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('搜索用户失败', error)
    ElMessage.error('搜索用户失败，请稍后重试')
  }
}

// 重置搜索
const resetSearch = () => {
  searchParams.phone = ''
  searchParams.role = ''
  pagination.currentPage = 1
  search()
}

// 分页事件处理
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  search()
}

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  search()
}

// 处理选中行变化
// const handleSelectionChange = (val) => {
//   console.log('选中的用户:', val)
// }

// 编辑用户
const editUser = async(row) => {
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  userForm.value = { ...row }
  console.log(userForm.value.role);
  
  //   try {
  //   // 发送请求，根据ID查询信息
  //   const result = await queryUserByIdApi(id);

  //   if (result.code === 200) {
  //     Object.assign(userForm, result.data);
  //   }
  // } catch (error) {
  //   console.error("获取风景项目信息失败:", error);
  //   ElMessage.error("获取数据失败，请稍后重试");
  // }
}

// 保存用户
const saveUser = async() => {
  if (!userFormRef.value) return
  
  userFormRef.value.validate(async(valid) => {
    if (valid) {
      if (userForm.value.id) {
       await updateUserApi(userForm.value.id,userForm.value).then(result => {
          if (result.code === 200) {
            ElMessage.success('用户更新成功')
            dialogVisible.value = false
            search()
          } else {
            ElMessage.error(result.message || '更新用户失败')
          }
        }).catch(error => {
          console.error('更新用户失败', error)
          ElMessage.error('更新用户失败，请稍后重试')
        })
      } 
    } else {
      ElMessage.error('请完善用户信息')
      return false
    }
  })
}

// 删除用户
const deleteUser = (id) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteUserApi(id).then(result => {
      if (result.code === 200) {
        ElMessage.success('用户删除成功')
        search()
      } else {
        ElMessage.error(result.message || '删除用户失败')
      }
    }).catch(error => {
      console.error('删除用户失败', error)
      ElMessage.error('删除用户失败，请稍后重试')
    })
  }).catch(() => {
    // 取消删除
  })
}








</script>

<style scoped>
.tableBody {
  width: 100%;
}



.content {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 内容左对齐 */
  padding: 0 20px;
}

.form {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 表单内容左对齐 */
}

.el-form-item {
  margin-right: 20px; /* 增加表单元素间距 */
}

.el-form-item:last-child {
  margin-right: 0;
}

.el-pagination {
  margin: 10px 0 20px 0;
  float: none; /* 取消浮动，改为左对齐 */
}

/* 表格样式优化 */
.el-table th {
  background-color: #f5f7fa;
}

.el-table .el-button {
  margin-right: 5px;
}
</style>